﻿using Mapster;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Transactions;
using WorldmeServer.Attributes;
using WorldmeServer.DTO.材质相关;
using WorldmeServer.DTO.游戏相关;
using WorldmeServer.Models.Base;
using WorldmeServer.Models.材质相关;
using WorldmeServer.Models.游戏相关;
using WorldmeServer.Models.用户相关;
using WorldmeServer.Models.衣柜相关;
using WorldmeServer.Services.Business.衣柜相关;
using WorldmeServer.Services.Database;
using WorldmeServer.Utils;

namespace WorldmeServer.Services.Business.材质相关
{
    [ScopedRegistration]
    public class TextureService
    {
        private readonly MySqlContext mysql;
        public TextureService(MySqlContext mysql)
        {
            this.mysql = mysql;
        }

        public async Task<ServiceResult<Texture>> GetTexture(string id)
        {
            var texture = await mysql.Textures.FirstOrDefaultAsync(t => t.Id == id);
            if (texture == null)
            {
                return ServiceResult<Texture>.Fail("材质不存在");
            }
            return ServiceResult<Texture>.Success(texture);
        }

        public async Task<ServiceResult<List<Texture>>> GetTextures(string userId)
        {
            if (!await mysql.Users.AnyAsync(u => u.Id == userId))
            {
                return ServiceResult<List<Texture>>.Fail("用户不存在");
            }
            var textures = await mysql.Textures.Where(x => x.UserId == userId).ToListAsync();
            return ServiceResult<List<Texture>>.Success(textures);
        }

        public async Task<ServiceResult<Texture>> Upload(string userId, IFormFile file, UploadTextureDto dto)
        {

            if (string.IsNullOrEmpty(dto.Name))
            {
                return ServiceResult<Texture>.Fail("材质名称不能为空");
            }
            if (await mysql.Textures.AnyAsync(t => t.Name == dto.Name))
            {
                return ServiceResult<Texture>.Fail("材质名称已存在");
            }
            Texture texture = dto.Adapt<Texture>();
            using (var transaction = mysql.Database.BeginTransaction())
            {
                try
                {
                    texture.Id = RandomUtils.GenerateNumble(6);
                    texture.UserId = userId;
                    string filepath = Path.Combine(Constant.PATH_TEXTURE, texture.Id);
                    using (FileStream fs = File.Create(filepath))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    };
                    // 添加到材质表
                    await mysql.Textures.AddAsync(texture);
                    await mysql.SaveChangesAsync();
                    // 添加到上传者衣柜
                    await mysql.Closets.AddAsync(new Closet
                    {
                        UserId = userId,
                        TextureId = texture.Id
                    });
                    await mysql.SaveChangesAsync();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    return ServiceResult<Texture>.Fail(ex.Message);
                }
            }
            return ServiceResult<Texture>.Success(texture);
        }

        public async Task<ServiceResult<Boolean>> DeleteTexture(string userId, string id)
        {
            var texture = await mysql.Textures.FirstOrDefaultAsync(t => t.Id == id);
            if (texture == null)
            {
                return ServiceResult<Boolean>.Fail("材质不存在");
            }
            if (texture.UserId != userId)
            {
                return ServiceResult<Boolean>.Fail("无权限删除");
            }
            mysql.Textures.Remove(texture);
            await mysql.SaveChangesAsync();
            return ServiceResult<Boolean>.Success(true);
        }

        public async Task<ServiceResult<Texture>> UpdateTexture(string userId, UpdateTextureDto dto)
        {
            var texture = await mysql.Textures.FirstOrDefaultAsync(t => t.Id == dto.Id);
            if (texture == null)
            {
                return ServiceResult<Texture>.Fail("材质不存在");
            }
            if (texture.UserId != userId)
            {
                return ServiceResult<Texture>.Fail("无权限修改");
            }
            texture.Name = dto.Name;
            texture.Type = dto.Type;
            texture.IsPrivate = dto.IsPrivate;
            mysql.Textures.Update(texture);
            await mysql.SaveChangesAsync();
            return ServiceResult<Texture>.Success(texture);
        }
    }
}
